package com.fotkidemo;


import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import com.fotkidemo.beans.Image;
import com.fotkidemo.network.json.AbstractJsonEntryParser;
import com.fotkidemo.network.json.JsonImagesParser;
import com.fotkidemo.tasks.DownloadAndParseEntryTask;
import com.fotkidemo.util.DiskCache;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: roma
 * Date: 6/23/12
 * Time: 2:52 PM
 * To change this template use File | Settings | File Templates.
 */

//Отображение фоток в GridView
public class ImagesFragment extends Fragment implements AdapterView.OnItemClickListener {
    private static final String TAG = "ImagesFragment";
    private static final String IMAGE_URL = "image_url";
    private static final String ALBUM_CACHE = "album_cache";
    private String URL;
    private String album_cache;
    private OnImagesClickListener listener;

    /**
     * Через данный интерфейс фрагмент связывается с activity, и в activity обрабатывается событие нажатия на фото.
     */
    public interface OnImagesClickListener {
        void onImageClick(Image image, int position);
    }

    public static ImagesFragment newInstance(String URL, String album_cache) {
        final ImagesFragment f = new ImagesFragment();

        final Bundle args = new Bundle();
        args.putString(IMAGE_URL, URL);
        args.putString(ALBUM_CACHE, album_cache);
        f.setArguments(args);

        return f;
    }

    public ImagesFragment() { }

    private ImageAdapter imageAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        URL = getArguments() != null ? getArguments().getString(IMAGE_URL) : "";
        album_cache = getArguments() != null ? getArguments().getString(ALBUM_CACHE) : "";

        DiskCache cache = DiskCache.initAndCreate(getActivity(), album_cache);
        imageAdapter = new SmallImageAdapter(cache);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.images, container, false);
        final GridView imagesView = (GridView) v.findViewById(R.id.imagesView);

        imagesView.setAdapter(imageAdapter);

        if (BuildConfig.DEBUG)
            Log.d(TAG, new StringBuilder("Get json images entry from url= ").append(URL).toString());

        //Получить информацию о фотках определенного альбома
        new DownloadAndParseImagesTask(imagesView).execute(URL);

        imagesView.setOnItemClickListener(this);

        return v;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            listener = (OnImagesClickListener) activity;
        } catch (ClassCastException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Image image = (Image) adapterView.getItemAtPosition(i);

        listener.onImageClick(image, i);
    }

    //Асинхронное выполнение запроса на фотки альбома
    private class DownloadAndParseImagesTask extends DownloadAndParseEntryTask<Image> {
        private GridView view;

        private DownloadAndParseImagesTask(GridView view) {
            this.view = view;
        }

        @Override
        public void onCompleteTask(List<Image> entries) {
            if (BuildConfig.DEBUG)
                Log.d(TAG, "set images adapter");

            imageAdapter.setImages(entries);
            view.setAdapter(imageAdapter);
        }

        @Override
        public String getTag() {
            return TAG;
        }

        @Override
        public AbstractJsonEntryParser getJsonParser(String json) {
            return new JsonImagesParser(json);
        }
    }


    private static class SmallImageAdapter extends ImageAdapter {
        public SmallImageAdapter(DiskCache cache) {
            super(cache);
        }

        @Override
        public String getHref(Image image) {
            return image.getHrefXXS();
        }
    }
}
